<?php

namespace catchAdmin\phone\model;

use catchAdmin\model\NeedMatchUser;
use catchAdmin\model\Notice;
use catchAdmin\model\wechat\PaymentApp;
use catchAdmin\model\WechatUserPayment;
use catcher\exceptions\AlertErrorException;
use think\facade\Config;

class Need extends \catchAdmin\model\Need
{

    public function saveData($param)
    {
        $this->startTrans();

        $msg = $this->saveDataApp($param);

        // 2.发消息
        (new Notice())->saveDataCC([
            // 需求审核——待审核
            'notice_type'    => 3,
            'title'          => '待审核',
            'content'        => "等待后台审核",
            'wechat_user_id' => $msg['wechat_user_id'],
        ]);

        $this->commit();

        return 1;
    }


    public function finish($param)
    {
        $msg = $this
            ->where([
                'id'             => $param['id'],
                'wechat_user_id' => $this->getLoginId(),
            ])
            ->find();
        if (empty($msg)) {
            throw new AlertErrorException();
        }
        if ($msg['need_status'] == 2) {
            throw new AlertErrorException();
        }

        $msg->need_status = 2;
        $msg->stage = 4;
        $msg->save();

        return 1;
    }


    /**
     * 充值
     */
    public function pay($param)
    {
        $pay_value = 9.9;

        // 检测需求信息是否是未支付
        {
            $need_match_user_msg = (new \catchAdmin\model\NeedMatchUser())
                ->where('need_id', $param['need_id'])
                ->where('wechat_user_id', $this->getLoginId())
                ->find();
            if (empty($need_match_user_msg)) {
                $need_match_user_msg = (new \catchAdmin\model\NeedMatchUser())->saveDataCC([
                    'need_id'        => $param['need_id'],
                    'wechat_user_id' => $this->getLoginId(),
                ]);
            }

            if ($need_match_user_msg['status'] == 2) {
                throw new AlertErrorException('已支付，不能重复支付');
            }
            if ($need_match_user_msg['status'] == 3) {
                throw new AlertErrorException('已完成，不能重复支付');
            }

            $need_match_user_msg->pay_amount = $pay_value;
            $need_match_user_msg->save();
        }

        $wechat_user_msg = (new \catchAdmin\model\WechatUser())
            ->where('id', $this->getLoginId())
            ->find();

        // 余额足够时，自动支付
        if ($wechat_user_msg['balance'] > $pay_value) {
            $this->startTrans();

            // 1.支付
            (new \catchAdmin\model\WechatUserBalance())->saveWechatUserBalance([
                'wechat_user_id' => $wechat_user_msg['id'],
                'balance_type'   => 1,
                'balance_type_2' => 103,
                'num'            => $pay_value,
                'out_trade_no'   => '',
            ]);

            // 2.需求信息变已支付
            $need_match_user_msg->pay_type = 1;
            $need_match_user_msg->pay_time = time();
            $need_match_user_msg->status = 2;
            $need_match_user_msg->save();

            $this->commit();

            return 1;
        }

        // 余额不足时，微信支付
        $trade_type_int = $param['trade_type'] ?? 2;
        // 1.公众号
        if ($trade_type_int == 1) {
            $app_id = Config::get("wechat.FuWuHaoApp.app_id");
            $openid = $wechat_user_msg['openid'];
            // 2.小程序
        } elseif ($trade_type_int == 2) {
            $app_id = Config::get("wechat.MiniProgramApp.app_id");
            $openid = $wechat_user_msg['mini_openid'];
        } else {
            throw new AlertErrorException('参数异常');
        }

        $this->startTrans();

        // 1.支付信息
        $payment_msg = (new WechatUserPayment())->saveDataCC([
            'mch_id' => Config::get("wechat.PaymentApp.mch_id"),
            'app_id' => $app_id,
            'openid' => $openid,

            'wechat_user_id' => $this->getLoginId(),
            'out_trade_no'   => time() . rand(1000, 9999),
            'body'           => '消费' . $pay_value,
            'total_fee'      => $pay_value,
            'zeng_value'     => 0,
            'trade_type_int' => $trade_type_int,
            'trade_type'     => "JSAPI",
            'balance_type'   => 90,
            'balance_type_2' => 9001,
        ]);

        // 2.返回前端信息
        $pay_send = (new PaymentApp($app_id))->payInit([
            'trade_type'   => $payment_msg['trade_type'],
            'body'         => $payment_msg['body'],
            'out_trade_no' => $payment_msg['out_trade_no'],
            'total_fee'    => $payment_msg['total_fee'],
            'notify_url'   => '/Notify/needPay',
            'openid'       => $openid,
        ]);

        $payment_msg->pay_send = json_encode($pay_send);
        $payment_msg->save();

        // 3.需求信息绑定支付id
        $need_match_user_msg->wechat_user_payment_id = $payment_msg['id'];
        $need_match_user_msg->save();

        $this->commit();

        return $pay_send;
    }

    ######################################## 显示 ################################################


    /**
     * 列表
     */
    public function indexData($param)
    {
        $app = $this
            ->where('wechat_user_id', $this->getLoginId())
            ->order('id desc');

        $list = $this->indexDataCC($param, $app);

        if (!empty($param['stage'])) {
            if ($param['stage'] == 2) {
                foreach ($list['list'] as &$item) {
                    $item['bao_num'] = (new NeedMatchUser())
                        ->where('pay_time', '>', 0)
                        ->where('need_id', $item['id'])
                        ->count();
                }
            }
        }

        return $list;
    }


    public function indexPub($param)
    {
        $app = $this
            ->where('status', 2)
            ->where('need_ent_date', '>=', date('Y-m-d'));

        if (!empty($param['order'])) {
            if ($param['order'] == 'publish_time_show') {
                $app = $app->order('publish_time', 'desc');
            } elseif ($param['order'] == 'need_ent_date') {
                $app = $app->order('need_ent_date', 'asc');
            }
        }

        $list = $this->indexDataCC($param, $app, ['left_day']);

        $list_2 = [];
        foreach ($list['list'] as $v) {
            $list_2[] = [
                'id'                  => $v['id'],
                'need_title'          => $v['need_title'],
                'project_jia_ji'      => $v['project_jia_ji'],
                'project_jia_ji_name' => $v['project_jia_ji_name'],
                'need_city_name'      => $v['need_city_name'],
                'company_type_name'   => $v['company_type_name'],
                'publish_time_show'   => $v['publish_time_show'],
                'need_ent_date'       => $v['need_ent_date'],
                'left_day'            => $v['left_day'],
                'pay_amount'          => 9.9,
            ];
        }

        $list['list'] = $list_2;

        return $list;
    }


    public function indexMatchUser($param)
    {
        $sql = "id in (";
        $sql .= " select need_id from need_match_user where wechat_user_id = " . $this->getLoginId();
        if (!empty($param['status'])) {
            $sql .= " and status = " . $param['status'];
        }
        $sql .= ")";

        $app = $this
            ->order('id desc');

        if ($param['status'] == 1) {
            $app = $app
                ->where('need_ent_date', ">", date('Y-m-d'));
        } else {
            $app = $app
                ->where($sql);
        }

        $list = $this->indexDataCC($param, $app, ['left_day']);

        $list_2 = [];
        foreach ($list['list'] as $v) {
            $list_2[] = [
                'id'                  => $v['id'],
                'company_type'        => $v['company_type'],
                'need_title'          => $v['need_title'],
                'need_city_name'      => $v['need_city_name'],
                'company_type_name'   => $v['company_type_name'],
                'publish_time_show'   => $v['publish_time_show'],
                'need_ent_date'       => $v['need_ent_date'],
                'left_day'            => $v['left_day'],
                'project_jia_ji'      => $v['project_jia_ji'],
                'project_jia_ji_name' => $v['project_jia_ji_name'],

                'goods_name' => $v['goods_name'],
                'goods_attr' => $v['goods_attr'],
                'goods_num'  => $v['goods_num'],

//                'pay_amount' => 9.9,
                'pay_amount' => 0,
            ];
        }
        $list['list'] = $list_2;

        return $list;
    }


    public function indexStage($param)
    {
        $list = $this->getStageLlist();

        foreach ($list as &$v) {
            $app = $this->where('wechat_user_id', $this->getLoginId());

            if (!empty($param['company_type'])) {
                $app = $app->where('company_type', $param['company_type']);
            }

            if (!empty($param['need_title'])) {
                $app = $app->whereLike('need_title', '%' . $param['need_title'] . '%');
            }

            $v['badge']['value'] = $app
                ->where('stage', $v['id'])
                ->count();

            if ($v['badge']['value'] > 0) {
                unset($v['disable']);
            } else {
                unset($v['badge']);
            }
        }

        return $list;
    }


    /**
     * 详情
     */
    public function read($param)
    {
        $msg = $this->readData($param);

        $show_link = false;

        $view_status = 0;
        if (empty($this->getLoginId())) {
            $view_status = 1;// 未登陆
        } else {
            $view_status = 2;// 登陆未认证
            if ($this->getLoginUser()['company_status'] == 3) {
                $view_status = 3;// 认证未支付
            }
            if ((new \catchAdmin\model\NeedMatchUser())
                ->where('need_id', $msg['id'])
                ->where('wechat_user_id', $this->getLoginId())
                ->where('pay_time', ">", 3)
                ->find()) {
                $view_status = 4;// 认证并支付
            }
        }

        $msg['view_status'] = $view_status;

        if ($msg['view_status'] == 4) {
            $show_link = true;
        }

        $self_fa = false;
        if ($msg['wechat_user_id'] == $this->getLoginId()) {
            $self_fa = true;
            $show_link = true;
        }

        $msg_1 = [
            'id'                => $msg['id'],
            'wechat_user_id'    => $msg['wechat_user_id'],
            'self_fa'           => $self_fa,
            'company_type'      => $msg['company_type'],
            'view_status'       => $msg['view_status'],
            'need_title'        => $msg['need_title'],
            'need_type'         => $msg['need_type'],
            'need_amount'       => $msg['need_amount'],
            'need_yao_qiu'      => $msg['need_yao_qiu'],
            'need_time'         => $msg['need_time'],
            'need_pay_type'     => $msg['need_pay_type'],
            'need_city_code'    => $msg['need_city_code'],
            'need_city_name'    => $msg['need_city_name'],
            'need_city_address' => $msg['need_city_address'],
            'company_yao_qiu'   => $msg['company_yao_qiu'],
            'need_ent_date'     => $msg['need_ent_date'],

            'goods_name' => $msg['goods_name'],
            'goods_attr' => $msg['goods_attr'],
            'goods_num'  => $msg['goods_num'],

            'company_name'     => '',
            'linkman_realname' => '',
            'linkman_duty'     => '',
            'linkman_mobile'   => '',

            'pay_amount'   => 9.9,
            'user_balance' => $this->getLoginUser()['balance'] ?? 0,

        ];

        if (!$show_link) {
            return $msg_1;
        }

        $msg_1['company_name'] = $msg['company_name'];
        $msg_1['linkman_realname'] = $msg['linkman_realname'];
        $msg_1['linkman_duty'] = $msg['linkman_duty'];
        $msg_1['linkman_mobile'] = $msg['linkman_mobile'];
        $msg_1['show_note'] = '您已购买本条信息，您的联系方式已在对方的求购列表中呈现';

        if ($msg_1['company_type'] == 3) {
            $msg_1['goods_name'] = $msg['goods_name'];
            $msg_1['goods_attr'] = $msg['goods_attr'];
            $msg_1['goods_num'] = $msg['goods_num'];
        }

        return $msg_1;
    }

}
